package com.hh.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.common.DeleteRequest;
import com.hh.common.ErrorCode;
import com.hh.entity.domain.Notice;
import com.hh.entity.domain.User;
import com.hh.entity.dto.notice.NoticeAddRequest;
import com.hh.entity.dto.notice.NoticeQueryRequest;
import com.hh.entity.dto.notice.NoticeUpdateRequest;
import com.hh.entity.vo.NoticeVO;
import com.hh.entity.vo.UserVO;
import com.hh.exception.BusinessException;
import com.hh.exception.ThrowUtils;
import com.hh.mapper.NoticeMapper;
import com.hh.service.NoticeService;
import com.hh.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author hanhui
 * @description 针对表【notice】的数据库操作Service实现
 * @createDate 2025-03-05 22:21:11
 */
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice>
        implements NoticeService {


    @Resource
    private UserService userService;

    @Override
    public Notice addNotice(NoticeAddRequest noticeAddRequest, User loginUser) {
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        String title = noticeAddRequest.getTitle();
        String content = noticeAddRequest.getContent();
        if (title == null || title.isEmpty()) {
            throw new BusinessException(ErrorCode.NOTICE_TITLE_NULL, "公告标题不能为空");
        }
        if (content == null || content.isEmpty()) {
            throw new BusinessException(ErrorCode.NOTICE_CONTENT_NULL, "公告内容不能为空");
        }
        noticeAddRequest.setPublishTime(new Date());
        Long id = loginUser.getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL);
        }

        //补充属性
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeAddRequest, notice);
        notice.setCreatorId(id);
        boolean saved = this.save(notice);
        if (!saved) {
            throw new BusinessException(ErrorCode.NOTICE_CREATE_ERROR, "添加公告失败");
        }
        return notice;
    }

    /**
     * 删除公告
     *
     * @param deleteRequest
     * @param loginUser
     */
    @Override
    public void deleteNotice(DeleteRequest deleteRequest, User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_NULL);
        Long id = deleteRequest.getId();
        Notice notice = this.getById(id);
        if (notice == null) {
            throw new BusinessException(ErrorCode.NOTICE_NOT_FOUND, "公告未找到");
        }
        this.removeById(id);
    }

    @Override
    public void updateNotice(NoticeUpdateRequest noticeUpdateRequest, User loginUser) {
        //登录校验
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        //参数校验
        ThrowUtils.throwIf(noticeUpdateRequest == null, ErrorCode.PARAMS_NULL);
        Long id = noticeUpdateRequest.getId();
        String title = noticeUpdateRequest.getTitle();
        String content = noticeUpdateRequest.getContent();
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_NULL);
        ThrowUtils.throwIf(title == null || title.isEmpty(), ErrorCode.NOTICE_TITLE_NULL);
        ThrowUtils.throwIf(content == null || content.isEmpty(), ErrorCode.NOTICE_CONTENT_NULL);
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeUpdateRequest, notice);
        notice.setUpdateTime(new Date());
        this.updateById(notice);
    }

    @Override
    public NoticeVO getNoticeVo(Notice notice, HttpServletRequest request) {
        NoticeVO noticeVO = NoticeVO.objToVo(notice);
        Long creatorId = notice.getCreatorId();
        if (creatorId != null && creatorId > 0) {
            User user = userService.getById(creatorId);
            UserVO userVo = userService.getUserVo(user);
            noticeVO.setUser(userVo);
        }
        return noticeVO;
    }

    @Override
    public Page<NoticeVO> getNoticeVoPage(Page<Notice> noticePage) {
        List<Notice> noticeList = noticePage.getRecords();
        Page<NoticeVO> noticeVOPage = new Page<>(noticePage.getCurrent(), noticePage.getSize(), noticePage.getTotal());
        if (CollUtil.isEmpty(noticeList)) {
            return noticeVOPage;
        }
        List<NoticeVO> noticeVOList = noticeList
                .stream()
                .map(NoticeVO::objToVo).collect(Collectors.toList());
        Set<Long> creatorIdSet = noticeList.stream().map(Notice::getCreatorId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(creatorIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        //  填充创建人
        noticeVOList.forEach(noticeVO -> {
            Long creatorId = noticeVO.getCreatorId();
            User user = null;
            if (userIdUserListMap.containsKey(creatorId)) {
                user = userIdUserListMap.get(creatorId).get(0);
            }
            noticeVO.setUser(userService.getUserVo(user));
        });
        noticeVOPage.setRecords(noticeVOList);
        return noticeVOPage;
    }

    @Override
    public QueryWrapper<Notice> getQueryWrapper(NoticeQueryRequest noticeQueryRequest) {
        if (noticeQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL);
        }
        Long id = noticeQueryRequest.getId();
        String title = noticeQueryRequest.getTitle();
        String content = noticeQueryRequest.getContent();
        int pageSize = noticeQueryRequest.getPageSize();
        int pageNum = noticeQueryRequest.getPageNum();
        String sortField = noticeQueryRequest.getSortField();
        String sortOrder = noticeQueryRequest.getSortOrder();

        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.like(title != null, "title", title);
        queryWrapper.like(content != null, "content", content);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


}




